package LeetCode.leetcode;

import domain.ListNode;

/**
 * 删除链表的倒数第N个节点
 * @author: leiwenkang02@meituan.com
 * @date: 2018/9/25
 * @time: 10:01
 */
public class Test19删除链表的倒数第N个节点 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode before = new ListNode(0);
        before.next = head;
        ListNode p1 = before;
        ListNode p2 = before;
        for (int i = 0; i <= n; i++) {
            if (p2 == null) {
                return null;
            }
            p2 = p2.next;
        }
        while (p2 != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
        p1.next = p1.next.next;
        return before.next;
    }
}
